#include "../include/dir_stack.h"

int dir_stack_init(dir_stack_t *dstack){
    dir_node_t *Nnode = (dir_node_t *)calloc(1,sizeof(dir_node_t));
    ERROR_CHECK(Nnode,NULL,"new node calloc");
    const char *p = "fu/";
    int length = strlen(p);
    int i;
    for(i=0;i<length;i++){
        Nnode->data[i] = p[i];
    }
    Nnode->data[i] = '\0';
    Nnode->next = NULL;
    dstack->top = Nnode;
    dstack->bottom = Nnode;
    dstack->size = 1;
    return 0;
}

int push_dir(dir_stack_t *dstack,char *dir){
    /* dir_node_t *Nnode = (dir_node_t *)calloc(1,sizeof(dir_node_t)); */
    /* ERROR_CHECK(Nnode,NULL,"new node calloc"); */
    /* strcpy(Nnode->data,dir); */
    /* Nnode->next = NULL; */
    /* dstack->top->next = Nnode; */
    /* dstack->top = Nnode; */
    /* dstack->size++; */
    dir_node_t *Nnode = (dir_node_t *)calloc(1,sizeof(dir_node_t));
    ERROR_CHECK(Nnode,NULL,"new node calloc");
    strcat(dir,"/");
    strcpy(Nnode->data,dir);
    Nnode->next = NULL;
    dstack->top->next = Nnode;
    dstack->top = Nnode;
    dstack->size++;
    return 0;
}

int pop_dir(dir_stack_t *dstack){
    if(dstack->size == 1){
        return -1;
    }
    else{
        dir_node_t *tem = dstack->bottom;
        while(tem->next != dstack->top){
            tem = tem->next;
        }
        dstack->top = tem;
        tem = tem->next;
        free(tem);
        dstack->top->next = NULL;
        dstack->size--;
    }
    return 0;
}

int traverse_dir_stack(dir_stack_t *dstack,char *dir){
    dir_node_t *tem = dstack->bottom;
    while(tem!=NULL){
        strcat(dir,tem->data);
        tem = tem->next;
    }
    printf("\n");
    return 0;
}

int reinit_dir_stack(dir_stack_t *dstack){
    dir_node_t *tem = dstack->bottom->next;
    dstack->bottom->next = NULL;                                                                                                                                               
    while(tem != NULL){
        dir_node_t *next = tem->next;
        free(tem);
        tem = next;
    }   
    return 0;
}

